<script>
import request from "../../utils/Request.js";
import { ElMessage } from "element-plus";
import { MdPreview, MdCatalog } from "md-editor-v3";
import "md-editor-v3/lib/style.css";

export default {
  components: { MdPreview, MdCatalog },
  name: "MarkdownView",
  props: {
    id: String,
    markdownText: String,
  },

  watch: {
    id(oV, nV) {
      if (oV !== nV) {
        this.getContent();
      }
    },
  },

  methods: {
    getContent() {
      request({
        url: "/api/project/markdown/content",
        method: "post",
        data: {
          projectId: this.$route.params.projectId,
          id: this.id,
        },
      }).then(({ data }) => {
        if (data.code === 0) {
          // this.context = data.data == null ? '' : this.markdown.render(data.data)
          this.context = data.data == null ? "" : data.data;
        } else {
          ElMessage.error(data.msg);
        }
      });
    },

    clickCatalog(e, t) {
      e.preventDefault();
      const el = document.getElementById(t.text);
      // 滚动到对应的位置
      // console.log(this.scrollElement)
      this.scrollElement.scrollTo({
        top: el.scrollTop - 20,
        behavior: "smooth",
      });
    },
  },

  data() {
    return {
      context: "",
      scrollElement: document.getElementsByTagName("main")[0],
      catalogDrawer: false,
    };
  },

  created() {
    if (this.markdownText != null) {
      this.context = this.markdownText;
    } else {
      this.getContent();
    }
  },
};
</script>

<template>
  <div style="width: 100%; height: 100%">
    <MdPreview :editorId="'md-p-md' + id" :modelValue="context" />

    <el-drawer
      v-model="catalogDrawer"
      title="CONTENTS"
      :modal="true"
      modal-class="drawer-modal"
      :lock-scroll="false"
      :show-close="false"
      size="20%"
    >
      <MdCatalog
        :editorId="'md-p-md' + id"
        :scrollElement="scrollElement"
        @onClick="clickCatalog"
      />
    </el-drawer>

    <div class="catalog-btn" @click="catalogDrawer = !catalogDrawer">
      <MdCatalog
        :editorId="'md-p-md' + id"
        :scrollElement="scrollElement"
        @onClick="clickCatalog"
      />
    </div>
  </div>
</template>

<style>
.drawer-modal {
  background: transparent;
}

.catalog-btn {
  font-size: smaller;
  color: rgba(44, 44, 44, 0.8);
  position: fixed;
  top: 50px;
  right: 20px;
  z-index: 999;
  padding: 10px;
  /* border-radius: 5px; */
  background: rgba(255, 255, 255, 0.2);
  /* 只有左边有阴影 */
  border-left: 2px solid rgba(78, 78, 78, 0.4);
  /* box-shadow: 0 0 10px rgba(0,0,0,0.1); */
  cursor: pointer;
}

.catalog-btn:hover {
  background: rgba(255, 255, 255, 0.8);
  /*动画 */
  transition: all 0.3s ease-in-out;
}
</style>